<template>
	<div v-show="websocket==null">
		我的用户id:<input v-model="userid" />
		<button @click="initopen">连接服务器</button>
	</div>
	<div v-show="websocket!=null">
		发送给好友的id:<input v-model="friendid" /><br>
		发送的内容:<textarea v-model="messagebody"></textarea>
		<br>
		<button @click="sendmessage">发送</button>
		<div>
			<div v-for="obj in bodycontentarr">
				<div v-show="obj.bs=='a'" style="text-align: right;">
					我:{{obj.message}}
				</div>
				<div v-show="obj.bs=='b'" style="text-align: left;">
					好友{{obj.src}}发给我的:{{obj.message}}
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	const userid = ref() //当前用户id
	const friendid = ref() //好友id
	const messagebody = ref("") //发送的内容
	const bodycontentarr = ref([]) //发送及接收的内容数组

	const websocket = ref();

	function sendmessage() { //单击发送按钮调用
		let obj = {
			"to": friendid.value, //发送给谁
			"messagebody": messagebody.value, //发送的内容
			"from": userid.value, //发送者的id(当前用户的id)
		}
		websocket.value.send(JSON.stringify(obj)) //发送到服务器端

		let body = {
			"bs": "a",
			"message": messagebody.value,
			"src": userid.value
		}
		bodycontentarr.value.push(body);

	}

	function initopen() {
		//判断当前浏览器是否支持WebSocket
		if ('WebSocket' in window) {
			websocket.value = new WebSocket("ws://192.168.161.161:8080/websocket/" + userid.value);
		} else {
			alert('Not support websocket')
		}

		//连接成功建立的回调方法
		websocket.value.onopen = function(event) {
			console.log("建立服务器连接成功")
		}

		//只要接受的服务器的消息，就会触发这个方法
		websocket.value.onmessage = function(event) {
			let res = JSON.parse(event.data)
			if (res.bs == "send") {
				let body = {
					"bs": "b",
					"message": res.message,
					"src": res.src
				}
				bodycontentarr.value.push(body);
				console.log(res.bs, res.message, res.src);
			}

		}
	}
</script>

<style>
</style>